// 非线程安全的观察者模式实现。
#include <algorithm>
#include <vector>
#include <stdio.h>

class Observable;

class Observer {
public:	
	virtual ~Observer();
	virtual void Update() = 0;

	void Observe(Observable *s);

protected:
	Observable *_subject;
};

class Observable {
public:
	void Register(Observer *x) {
		_observers.push_back(x);
	}

	void Unregister(Observer *x) {
		std::vector<Observer*>::iterator it = std::find(_observers.begin(), _observers.end(), x);
		if (it != _observers.end()) {
			std::swap(*it, _observers.back());
			_observers.pop_back();
		}
	}

	void NotifyObservers() {
		for (size_t i = 0; i < _observers.size(); ++i) {
			Observer *x = _observers[i];
			if (x)
				x->Update();
		}
	}

private:
	std::vector<Observer*> _observers;
};

Observer::~Observer() {
	_subject->Unregister(this);
}

void
Observer::Observe(Observable *s) {
	s->Register(this);
	_subject = s;
}

class Foo : public Observer {
	virtual void Update() {
		printf("Foo::Update %p\n", this);
	}
};

int 
main() {
	Foo *p = new Foo();
	Observable subject;
	p->Observe(&subject);
	subject.NotifyObservers();
	delete p; // p 在析构函数中调用了 Unregister 。
	subject.NotifyObservers();
}
